package cn.seaboot.admin.excel.web;

import cn.seaboot.admin.excel.manager.ExcelTemplateService;
import cn.seaboot.admin.mvc.argument.Params;
import cn.seaboot.commons.file.FilenameUtils;
import cn.seaboot.commons.file.ResponseWriter;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/**
 * Excel 模版 - Controller
 *
 * @author ChenSS on 2018/6/27.
 * @version 1.0.0
 */
@Controller
@Tag(name = "Excel 模版 管理")
@RequestMapping("sys/excel/tpl")
public class ExcelTemplateCtrl {

    @Resource
    private ExcelTemplateService excelTemplateService;

    /**
     * 打开模版文件的输入流
     *
     * @param fileName 模版名称，例如：user
     * @throws IOException 文件未找到
     */
    @ResponseBody
    @Operation(description = "导出空的Excel模版")
    @Parameters({@Parameter(name = "fileName", description = "文件名")})
    @RequestMapping(value = "download", method = RequestMethod.GET)
    public void download(HttpServletRequest request, HttpServletResponse response
            , @Params String fileName) throws IOException {
        String name = FilenameUtils.getName(fileName);
        try (InputStream is = excelTemplateService.openInputStream(fileName)) {
            ResponseWriter.download(response, is, name);
        }
    }
}
